// www.jianshu.com/p/eb325d70990b?utm_medium=timeline
//第一步导入axios
import axios from "axios";
import QS from "qs";
import {Message,Loading} from 'element-ui'

//第二步新的常量axios
const http = axios.create({
  // baseURL: "http://data.cngy.gov.cn/",
  baseURL: "/api",
  // baseURL: "https://mockapi.eolink.com/",
  timeout: 4000, //设置超时时间
  responseType: "json",
  withCredentials: false, // 允许携带cookie
  changeOrigin: true, //是否跨域
});
// 第三步请求拦截
http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
http.defaults.headers.get["Content-Type"] = "application/x-www-form-urlencoded";
http.interceptors.request.use(
  config => {
		// Loading.service({text:"加载中..."});
    config.data = QS.stringify(config.data);
    config.headers.token = su.cook.getcookie("token");
    return config;
  },
  error => {
    console.log(error);
		Message.error({message: '请求超时!'});
    return Promise.reject(error);
  }
);
//第四步 设置响应拦截
http.interceptors.response.use(
  response => {
		// Loading.service().close();
    return response.data;
  },
  error => {
    if (error.response.status) {
      switch (error.response.status) {
        case 401:
          // router.replace({
          //   path: "/login",
          //   query: { redirect: router.currentRoute.fullPath },
          // });
          // break;
          console.log("未登录，到登录页");
        case 403:
          console.log("登录过期，删除登录信息");
          break;
        // 404请求不存在
        case 404:
          console.log("到404页面");
          break;
        // 其他错误，直接抛出错误提示
        default:
          console.log("其他状态，弹出错误信息");
      }
      return Promise.reject(error.response);
    }
  }
);

export default http;
